package ext.tianma.listener;

import java.beans.PropertyVetoException;
import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import ext.tianma.bom.util.DBUtil;
import ext.tianma.bom.util.GenericUtil;
import ext.tianma.doc.forms.CreateNewDocProcessor;
import ext.tianma.util.FileDownloadUtil;
import wt.content.ApplicationData;
import wt.content.ContentHelper;
import wt.content.ContentHolder;
import wt.content.ContentItem;
import wt.content.ContentRoleType;
import wt.content.ContentServerHelper;
import wt.content.ContentServiceEvent;
import wt.content.FormatContentHolder;
import wt.doc.WTDocument;
import wt.doc.WTDocumentDependencyLink;
import wt.fc.ObjectReference;
import wt.fc.Persistable;
import wt.fc.PersistenceHelper;
import wt.fc.PersistenceManagerEvent;
import wt.fc.PersistenceServerHelper;
import wt.fc.QueryResult;
import wt.folder.Folder;
import wt.folder.FolderEntry;
import wt.folder.FolderHelper;
import wt.inf.container.WTContainer;
import wt.inf.container.WTContainerRef;
import wt.log4j.LogR;
import wt.part.WTPart;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.type.TypeDefinitionReference;
import wt.type.TypedUtility;
import wt.util.WTException;
import wt.util.WTProperties;
import wt.vc.VersionControlHelper;
import wt.vc.wip.WorkInProgressHelper;

public class ListenerService {

	private static final Logger LOGGER = LogR.getLogger(ListenerService.class.getName());
	private static String softtype_InitialDrawingDoc = "cn.tianma.InitialDrawingDoc";// 原档图纸
	private static String softtype_ControlDocument = "cn.tianma.ControlDocument";// 受控PDF图纸

	private static String softtype_InitialDrawingDoc1 = "cn.tianma.ProcessOriginDrawingDoc";// 原档图纸
	private static String softtype_ControlDocument1 = "cn.tianma.ProcessDocuments";// 受控PDF图纸

	private static String containerName = "Asi产品库";// Asi产品库

	private static String templateFolder = null;
	public static String FolderPath;
	static {
		try {
			templateFolder = WTProperties.getLocalProperties().getProperty("wt.home");
			FolderPath = templateFolder + File.separator + "codebase" + File.separator + "temp";
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * 创建受控PDF图纸时 创建原档图纸,并创建说明关系
	 * 
	 * @param targetObj
	 * @param eventType
	 */
	public static void createInitialDrawingDocAndLink2(Object targetObj, String eventType) throws WTException {
		String softtype;
		if (eventType.equals(ContentServiceEvent.POST_UPLOAD)) {
			try {
				if (targetObj instanceof WTDocument) {
					WTDocument doc = (WTDocument) targetObj;
					// &&
					// VersionControlServiceEvent.NEW_VERSION.equals(eventType)
					// &&
					softtype = GenericUtil.getTypeId(doc);
					// 判断类型为受控PDF图纸 且 新建时
					ApplicationData appdata1 = getPrimaryContent(doc);
					// 获取受控PDF图纸附件
					ApplicationData appdata = null;
					QueryResult primaryresult2 = ContentHelper.service.getContentsByRole(doc, ContentRoleType.PRIMARY);
					QueryResult secondresult = ContentHelper.service.getContentsByRole(doc, ContentRoleType.SECONDARY);
					String docNameByapp = "";
					while (secondresult.hasMoreElements()) {
						ContentItem attachment = (ContentItem) secondresult.nextElement();
						if (attachment instanceof ApplicationData) {
							appdata = (ApplicationData) attachment;
							if (appdata != null) {
								String docName = appdata.getFileName();
								if (docName != "" || docName != null) {
									docNameByapp = docName.substring(0, docName.indexOf("."));
								}
								break;
							}

						}
					}

					ObjectReference derived = VersionControlHelper.getDerivedFrom(doc);
					if (derived == null || derived.getObject() == null && appdata != null
							&& softtype.indexOf(softtype_ControlDocument) != -1) {
						// 新建
						String version = VersionControlHelper.getIterationDisplayIdentifier(doc).toString();

						if ("0.0".equals(version)) {
							boolean checkout = WorkInProgressHelper.isCheckedOut(doc);
							if (!checkout) {
								// 创建原档图纸
								WTDocument document = createInitialDrawingDoc(doc, docNameByapp,
										softtype_InitialDrawingDoc);
								if (document != null) {
									System.out.println("=====document:" + document.getNumber());
								}
								// 原档图纸挂载主内容
								document = addContent(document, appdata);
								// 受控PDF文档移除附件
								// doc = deleteContent(doc);
								// 创建说明关系
								createDescripLink(document, doc);
							}
						}

					} else {
						System.out.println("NEW_VERSION.............new:" + doc.getNumber());
					}

				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	/**
	 * 创建受控PDF图纸时 创建原档图纸,并创建说明关系
	 * 
	 * @param targetObj
	 * @param eventType
	 */
	public static void createInitialDrawingDocAndLink(Object targetObj, String eventType) throws WTException {
		String softtype;
		if (eventType.equals(ContentServiceEvent.POST_UPLOAD)) {
			try {
				if (targetObj instanceof WTDocument) {
					WTDocument doc = (WTDocument) targetObj;
					// &&
					// VersionControlServiceEvent.NEW_VERSION.equals(eventType)
					// &&
					softtype = GenericUtil.getTypeId(doc);
					// 判断类型为受控PDF图纸 且 新建时
					ApplicationData appdata1 = getPrimaryContent(doc);
					// 获取受控PDF图纸附件
					ApplicationData appdata = null;
					QueryResult primaryresult2 = ContentHelper.service.getContentsByRole(doc, ContentRoleType.PRIMARY);
					QueryResult secondresult = ContentHelper.service.getContentsByRole(doc, ContentRoleType.SECONDARY);
					String docNameByapp = "";
					while (secondresult.hasMoreElements()) {
						ContentItem attachment = (ContentItem) secondresult.nextElement();
						if (attachment instanceof ApplicationData) {
							appdata = (ApplicationData) attachment;
							if (appdata != null) {
								String docName = appdata.getFileName();
								if (docName != "" || docName != null) {
									docNameByapp = docName.substring(0, docName.indexOf("."));
								}
								break;
							}

						}
					}

					ObjectReference derived = VersionControlHelper.getDerivedFrom(doc);
					if (derived == null || derived.getObject() == null && appdata != null
							&& softtype.contains(softtype_ControlDocument)) {
						// 新建
						String version = VersionControlHelper.getIterationDisplayIdentifier(doc).toString();

						if ("0.0".equals(version)) {
							boolean checkout = WorkInProgressHelper.isCheckedOut(doc);
							if (!checkout) {
								// 创建原档图纸
								WTDocument document = createInitialDrawingDoc(doc, docNameByapp,
										softtype_InitialDrawingDoc);
								if (document != null) {
									System.out.println("=====document:" + document.getNumber());
								}
								// 原档图纸挂载主内容
								document = addContent(document, appdata);
								// 受控PDF文档移除附件
								// doc = deleteContent(doc);
								// 创建说明关系
								createDescripLink(document, doc);
							}
						}

					} else if (derived == null || derived.getObject() == null && appdata != null
							&& softtype.contains(softtype_ControlDocument1)) {
						// 新建
						String version = VersionControlHelper.getIterationDisplayIdentifier(doc).toString();
						if ("0.0".equals(version)) {
							boolean checkout = WorkInProgressHelper.isCheckedOut(doc);
							if (!checkout) {
								// 创建原档图纸
								WTDocument document = createInitialDrawingDoc(doc, docNameByapp,
										softtype_InitialDrawingDoc1);
								if (document != null) {
									System.out.println("=====document:" + document.getNumber());
								}
								// 原档图纸挂载主内容
								document = addContent(document, appdata);
								// 受控PDF文档移除附件
								// doc = deleteContent(doc);
								// 创建说明关系
								createDescripLink(document, doc);
							}
						}
					}

				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	public static WTDocument createInitialDrawingDoc(WTDocument pdfdoc, String docName, String softtype) {
		System.out.println("====>>>start  4<<<=====");
		WTContainer container = pdfdoc.getContainer();
		if (container == null)
			return null;
		WTDocument document = null;
		try {
			document = WTDocument.newWTDocument();
			String number = DBUtil.getNextValue("WTDOCUMENTID_seq", 10);

			String name = DBUtil.getNextValue("variantnameseq", 10);
			// 名称
			document.setName(docName);
			// 类型
			TypeDefinitionReference typeDefinitionRef = TypedUtility.getTypeDefinitionReference(softtype);
			document.setTypeDefinitionReference(typeDefinitionRef);
			// 存储容器
			document.setContainerReference(WTContainerRef.newWTContainerRef(container));
			// 具体位置 与受控PDF图纸相同
			// String defaultFolderPath = "/Default";
			Folder oldFoler = FolderHelper.getFolder(pdfdoc);
			if (oldFoler == null) {
				String strLocation = pdfdoc.getLocation();
				oldFoler = FolderHelper.service.getFolder(strLocation, container.getContainerReference());
			}
			FolderHelper.assignLocation((FolderEntry) document, oldFoler);
			/*
			 * if(FOLDER_MAP.containsKey(logType))
			 * defaultFolderPath=FOLDER_MAP.get(logType); Folder
			 * folder=GenericUtil.getFolder(defaultFolderPath,container);
			 * FolderHelper.assignLocation((FolderEntry)document, folder);
			 */
			// 持久化
			document = (WTDocument) PersistenceHelper.manager.save(document);
			// 设置文档主内容
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return document;

	}

	/**
	 * 根据名称，获得容器
	 * 
	 * @param containerName
	 *            容器名称
	 */
	public static WTContainer getContainerByName(String containerName) {
		if (StringUtils.isEmpty(containerName))
			return null;
		try {
			QuerySpec queryspec = new QuerySpec(WTContainer.class);
			queryspec.appendWhere(
					new SearchCondition(WTContainer.class, WTContainer.NAME, SearchCondition.EQUAL, containerName),
					new int[] { 0 });
			QueryResult qr = PersistenceHelper.manager.find(queryspec);
			return qr.hasMoreElements() ? (WTContainer) qr.nextElement() : null;
		} catch (WTException e) {
			// e.printStackTrace();
			LOGGER.error(e.getMessage(), e);
		}
		return null;
	}

	/**
	 * 添加主内容
	 * 
	 * @param doc
	 * @param data
	 * @return
	 */
	public static WTDocument addContent(WTDocument doc, ApplicationData data) {
		if (doc != null) {
			try {
				ApplicationData newdata = ApplicationData.newApplicationData(doc);
				newdata.setRole(ContentRoleType.PRIMARY);

				if (data != null) {
					String path = FileDownloadUtil.FolderPath + File.separator + "PrimaryFileTemp" + File.separator
							+ "ControlDocument" + File.separator + data.getFileName();

					boolean flag = downloadPrimaryFile(doc, "ControlDocument", data.getFileName(), data);// 下载主内容到指定文件夹
					if (flag) {
						newdata.setFileName(data.getFileName());
						newdata.setUploadedFromPath(path);
						newdata = ContentServerHelper.service.updateContent(doc, newdata, path);
					}

					newdata = (ApplicationData) PersistenceHelper.manager.save(newdata);
					doc = (WTDocument) PersistenceHelper.manager.refresh((Persistable) doc);
					PersistenceServerHelper.manager.update(doc);
					File file = new File(path);
					if (file.exists()) {
						file.delete();
					}

				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return doc;
	}

	/**
	 * 移除受控PDF文档附件
	 * 
	 * @param doc
	 * @param data
	 * @return
	 */
	public static WTDocument deleteContent(WTDocument doc) {
		if (doc != null) {
			QueryResult result;
			try {
				result = ContentHelper.service.getContentsByRole(doc, ContentRoleType.SECONDARY);

				ApplicationData data = null;
				while (result.hasMoreElements()) {
					data = (ApplicationData) result.nextElement();
				}
				if (data != null) {
					ContentServerHelper.service.deleteContent(doc, data);
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return doc;
	}

	/**
	 * 受控文档关联原档图纸
	 * 
	 * @param control
	 * @param pdfdocument
	 */
	public static void createDescripLink(WTDocument control, WTDocument pdfdocument) {
		WTDocumentDependencyLink dependencyLink;
		try {
			if (control != null && pdfdocument != null) {
				dependencyLink = WTDocumentDependencyLink.newWTDocumentDependencyLink(pdfdocument, control);
				PersistenceServerHelper.manager.insert(dependencyLink);
			}
		} catch (WTException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public static ApplicationData getPrimaryContent(ContentHolder holder) throws WTException {
		ContentHolder contentHolder = null;
		ApplicationData applicationdata = null;
		try {
			contentHolder = ContentHelper.service.getContents(holder);
			LOGGER.debug("ContentHolder : " + contentHolder);
			ContentItem contentitem = ContentHelper.getPrimary((FormatContentHolder) contentHolder);
			LOGGER.debug("Primary : " + contentitem);
			applicationdata = (ApplicationData) contentitem;
		} catch (WTException e) {
			LOGGER.error("getPrimaryContent():", e);
			throw new WTException(e, e.getLocalizedMessage());
		} catch (Exception e) {
			LOGGER.error("getPrimaryContent():", e);
			throw new WTException(e, e.getLocalizedMessage());
		}
		return applicationdata;
	}

	/**
	 * 创建文件夹
	 * 
	 * @param diskPath
	 * @return
	 */
	public static String createDiskForder(String diskPath) {
		File file = new File(diskPath);
		if (!file.exists()) {// 如果文件夹不存在
			file.mkdirs();// 创建文件夹
		}
		return diskPath;
	}

	/**
	 * 下载主文件
	 * 
	 * @param contentHolder
	 * @param FolderName
	 * @return
	 * @throws WTException
	 */
	public static boolean downloadPrimaryFile(ContentHolder contentHolder, String FolderName, String fileName,
			ApplicationData data) throws WTException {

		String tempFolderPath = FolderPath + File.separator + "PrimaryFileTemp" + File.separator + FolderName;// 文件夹
		tempFolderPath = createDiskForder(tempFolderPath);
		FormatContentHolder aFormatContentHolder = null;
		boolean rtnValue = true;
		if (contentHolder == null) {
			return false;
		}
		try {
			aFormatContentHolder = (FormatContentHolder) ContentHelper.service.getContents(contentHolder);
		} catch (PropertyVetoException e1) {
			e1.printStackTrace();
		}
		ApplicationData primary = (ApplicationData) ContentHelper.getPrimary(aFormatContentHolder);
		if (data != null) {
			primary = data;
		}
		if (primary != null) {
			try {
				if (!"".equals(fileName) || fileName != null) {
					// tempFolderPath = tempFolderPath + File.separator +
					// fileName + "_" + primary.getFileName();
					tempFolderPath = tempFolderPath + File.separator + fileName;

				}
				ContentServerHelper.service.writeContentStream(primary, tempFolderPath);
			} catch (IOException e) {
				System.out.println("写文件错误" + tempFolderPath);
				rtnValue = false;
			}
		} else {
			rtnValue = false;
		}

		return rtnValue;
	}

	/**
	 * 编辑或 修订 受控PDF图纸时 更新附件内容至参考文档（原档图纸的主内容）
	 * 
	 * @param targetObj
	 * @param eventType
	 * @throws Exception
	 */
	public static void modifyInitialDrawingDocAndLink2(Object targetObj, String eventType) throws Exception {
		if (eventType.equals(PersistenceManagerEvent.POST_MODIFY)) {
			WTDocument doc = null;
			if (targetObj instanceof WTDocument) {
				doc = (WTDocument) targetObj;
				String softtype = GenericUtil.getTypeId(doc);
				// 判断类型为受控PDF图纸
				if (softtype.indexOf(softtype_ControlDocument) == -1) {
					return;
				}
				boolean checkout = WorkInProgressHelper.isCheckedOut(doc);
				/*
				 * if (checkout) { return; }
				 */
				// 判断 是否有附件
				boolean isControlDocument = CreateNewDocProcessor.checkAttacheByDOC(doc);
				if (!isControlDocument) {
					throw new WTException("请添加附件");
				} else {

					// 获取受控PDF图纸附件
					ApplicationData appdata = null;
					QueryResult secondresult = ContentHelper.service.getContentsByRole(doc, ContentRoleType.SECONDARY);

					QueryResult primary = ContentHelper.service.getContentsByRole(doc, ContentRoleType.PRIMARY);
					String docNameByapp = "";

					while (secondresult.hasMoreElements()) {
						ContentItem attachment = (ContentItem) secondresult.nextElement();
						if (attachment instanceof ApplicationData) {
							appdata = (ApplicationData) attachment;
							if (appdata != null) {
								System.out.println("===appdata:" + appdata.getFileName());
							}
							break;
						}

						String docName = appdata.getFileName();

						if (docName != "" || docName != null) {
							docNameByapp = docName.substring(0, docName.indexOf("."));
						}
					}

					// 获取说明文档
					WTDocument descripedoc = null;
					QueryResult qr = PersistenceHelper.manager.navigate(doc, "describedBy",
							WTDocumentDependencyLink.class, false);
					if (qr != null) {
						while (qr.hasMoreElements()) {
							WTDocumentDependencyLink link = (WTDocumentDependencyLink) qr.nextElement();
							WTDocument relateDoc = link.getDependsOn();
							String relatesofttype = GenericUtil.getTypeId(relateDoc);
							if (relatesofttype.indexOf(softtype_InitialDrawingDoc) != -1
									&& relateDoc.isLatestIteration()) {
								relateDoc = GenericUtil.getWTDocument(relateDoc.getNumber());
								if (appdata != null && relateDoc != null) {
									// 更新原档图纸的主内容
									updateContent(relateDoc, appdata);
								}
							}
						}
						// 旧受控PDF图纸不存在原档图纸时，新建link
					} else if (qr != null || qr.size() == 0) {
						// 创建原档图纸
						WTDocument document = createInitialDrawingDoc(doc, docNameByapp, softtype_InitialDrawingDoc);
						if (document != null && appdata != null) {
							// 原档图纸挂载主内容
							document = addContent(document, appdata);
							// 受控PDF文档移除附件
							// doc = deleteContent(doc);
							// 创建说明关系
							createDescripLink(document, doc);

						}
					}
				}

			}
			// 受控PDF文档移除附件
			if (doc != null) {
				doc = deleteContent(doc);
			}

		}
	}

	/**
	 * 更新主内容 及原档图纸名称
	 * 
	 * @param doc
	 * @param data
	 * @return
	 */
	public static WTDocument updateContent(WTDocument doc, ApplicationData data) {

		if (doc != null) {
			try {
				// 删除主内容
				ContentHolder contentholder = (ContentHolder) doc;
				contentholder = ContentHelper.service.getContents(contentholder);
				List contentListForTarget = ContentHelper.getContentListAll(contentholder);
				for (int i = 0; i < contentListForTarget.size(); i++) {
					ContentItem contentItem = (ContentItem) contentListForTarget.get(i);
					if (("PRIMARY").equals(contentItem.getRole().toString())) {
						ContentServerHelper.service.deleteContent(contentholder, contentItem);
						break;
					}
				}

				// 新增主内容
				ApplicationData newdata = ApplicationData.newApplicationData(doc);
				newdata.setRole(ContentRoleType.PRIMARY);
				if (data != null) {
					String path = FileDownloadUtil.FolderPath + File.separator + "PrimaryFileTemp" + File.separator
							+ "ControlDocument" + File.separator + data.getFileName();
					boolean flag = downloadPrimaryFile(doc, "ControlDocument", data.getFileName(), data);// 下载主内容到指定文件夹
					if (flag) {
						newdata.setFileName(data.getFileName());
						newdata.setUploadedFromPath(path);
						newdata = ContentServerHelper.service.updateContent(doc, newdata, path);
					}

					newdata = (ApplicationData) PersistenceHelper.manager.save(newdata);
					doc = (WTDocument) PersistenceHelper.manager.refresh((Persistable) doc);
					PersistenceServerHelper.manager.update(doc);
					File file = new File(path);
					if (file.exists()) {
						file.delete();
					}

					// 重置 原档图纸名称
					GenericUtil.setWTDocName(doc, data.getFileName().substring(0, data.getFileName().lastIndexOf(".")));

				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return doc;
	}

	/**
	 * 编辑或 修订 受控PDF图纸时 更新附件内容至参考文档（原档图纸的主内容）
	 * 
	 * @param targetObj
	 * @param eventType
	 * @throws Exception
	 */
	public static void modifyInitialDrawingDocAndLink(Object targetObj, String eventType) throws Exception {
		if (eventType.equals(PersistenceManagerEvent.POST_MODIFY)) {
			WTDocument doc = null;
			if (targetObj instanceof WTDocument) {
				doc = (WTDocument) targetObj;
				String softtype = GenericUtil.getTypeId(doc);
				// 判断类型为受控PDF图纸
				if (softtype.contains(softtype_ControlDocument)) {

					boolean checkout = WorkInProgressHelper.isCheckedOut(doc);
					/*
					 * if (checkout) { return; }
					 */
					// 判断 是否有附件
					boolean isControlDocument = CreateNewDocProcessor.checkAttacheByDOC(doc);
					if (!isControlDocument) {
						throw new WTException("请添加附件");
					} else {

						// 获取受控PDF图纸附件
						ApplicationData appdata = null;
						QueryResult secondresult = ContentHelper.service.getContentsByRole(doc,
								ContentRoleType.SECONDARY);
						QueryResult primary = ContentHelper.service.getContentsByRole(doc, ContentRoleType.PRIMARY);
						String docNameByapp = "";
						while (secondresult.hasMoreElements()) {
							ContentItem attachment = (ContentItem) secondresult.nextElement();
							if (attachment instanceof ApplicationData) {
								appdata = (ApplicationData) attachment;
								if (appdata != null) {
									System.out.println("===appdata:" + appdata.getFileName());
								}
								break;
							}
							String docName = appdata.getFileName();

							if (docName != "" || docName != null) {
								docNameByapp = docName.substring(0, docName.indexOf("."));
							}
						}

						// 获取说明文档
						WTDocument descripedoc = null;
						QueryResult qr = PersistenceHelper.manager.navigate(doc, "describedBy",
								WTDocumentDependencyLink.class, false);
						System.out.println("====>>>start  15<<<====="+qr.size());
						System.out.println("====>>>start  15<<<====="+qr);
						if (qr.size()>0) {
							while (qr.hasMoreElements()) {
								WTDocumentDependencyLink link = (WTDocumentDependencyLink) qr.nextElement();
								WTDocument relateDoc = link.getDependsOn();
								String relatesofttype = GenericUtil.getTypeId(relateDoc);
								if (relatesofttype.indexOf(softtype_InitialDrawingDoc) != -1
										&& relateDoc.isLatestIteration()) {
									relateDoc = GenericUtil.getWTDocument(relateDoc.getNumber());
									if (appdata != null && relateDoc != null) {
										// 更新原档图纸的主内容
										updateContent(relateDoc, appdata);
									}
								}
							}
							// 旧受控PDF图纸不存在原档图纸时，新建link
						} else if (qr != null || qr.size() == 0) {
							// 创建原档图纸
							WTDocument document = createInitialDrawingDoc(doc, docNameByapp,
									softtype_InitialDrawingDoc);
							if (document != null && appdata != null) {
								// 原档图纸挂载主内容
								document = addContent(document, appdata);
								// 受控PDF文档移除附件
								// doc = deleteContent(doc);
								// 创建说明关系
								createDescripLink(document, doc);

							}
						}
					}
					// 工艺文件附件创建工艺类原档图纸
				} else if (softtype.contains(softtype_ControlDocument1)) {
					System.out.println("====>>>start  0<<<=====");
					// 判断 是否有附件
					boolean isControlDocument = CreateNewDocProcessor.checkAttacheByDOC(doc);
					if (!isControlDocument) {
						return;
					} else {
						System.out.println("====>>>start  1<<<=====");
						ApplicationData appdata = null;
						QueryResult secondresult = ContentHelper.service.getContentsByRole(doc,
								ContentRoleType.SECONDARY);
						QueryResult primary = ContentHelper.service.getContentsByRole(doc, ContentRoleType.PRIMARY);
						String docNameByapp = "";
						while (secondresult.hasMoreElements()) {
							ContentItem attachment = (ContentItem) secondresult.nextElement();
							if (attachment instanceof ApplicationData) {
								appdata = (ApplicationData) attachment;
								if (appdata != null) {
									System.out.println("===appdata:" + appdata.getFileName());
								}
							}
							String docName = appdata.getFileName();
							if (docName != "" || docName != null) {
								docNameByapp = docName.substring(0, docName.indexOf("."));
								System.out.println("======>>>docNameByapp<<<======="+docNameByapp);
							}
						}

						// 获取说明文档
						WTDocument descripedoc = null;
						QueryResult qr = PersistenceHelper.manager.navigate(doc, "describedBy",
								WTDocumentDependencyLink.class, false);
						System.out.println("====>>>start  5<<<====="+qr.size());
						System.out.println("====>>>start  5<<<====="+qr);
						if (qr.size()>0) {
							System.out.println("====>>>start  3<<<====="+qr.hasMoreElements());
							while (qr.hasMoreElements()) {
								
								WTDocumentDependencyLink link = (WTDocumentDependencyLink) qr.nextElement();
								WTDocument relateDoc = link.getDependsOn();
								System.out.println("====>>>start  7<<<====="+relateDoc);
								String relatesofttype = GenericUtil.getTypeId(relateDoc);
								if (relatesofttype.indexOf(softtype_InitialDrawingDoc1) != -1
										&& relateDoc.isLatestIteration()) {
									relateDoc = GenericUtil.getWTDocument(relateDoc.getNumber());
									if (appdata != null && relateDoc != null) {
										// 更新原档图纸的主内容
										updateContent(relateDoc, appdata);
									}
								}
							}
							// 旧受控PDF图纸不存在原档图纸时，新建link
						} else if (qr != null || qr.size() == 0) {
							System.out.println("====>>>start  2<<<=====");
							// 创建原档图纸
							WTDocument document = createInitialDrawingDoc(doc, docNameByapp,
									softtype_InitialDrawingDoc1);
							if (document != null && appdata != null) {
								// 原档图纸挂载主内容
								document = addContent(document, appdata);
								// 受控PDF文档移除附件
								// doc = deleteContent(doc);
								// 创建说明关系
								createDescripLink(document, doc);

							}
						}
					}
				}

			}
			// 受控PDF文档移除附件
			if (doc != null) {
				doc = deleteContent(doc);
			}

		}
	}

}
